import {
  pick,
  isNotEmpty,
  isPlainObject,
  decode,
  camelCase,
  kebabCase,
  isFunction,
  clone,
  toBoolean,
  toNumber,
  split,
  toDefaultValue,
} from '@jecloud/utils';
import { FuncFieldTypeEnum } from './func-field-enum';
import FuncField from './func-field';
/**
 * 解析数据
 * @param {*} param0
 */
export function parseFunc({ func, options }) {
  const { fields } = options;
  parseFields({ func, data: fields });
}

/**
 * 解析字段信息
 * @param {*} data
 */
function parseFields({ func, data }) {
  // 基础数据
  const fields = data.map((item) => {
    const field = new FuncField(item);
    field.metaData = parseMetaData(field);
    //给readonly赋初始值
    field.metaData.readOnly = field.metaData.disabled;
    func.basic.fields.set(field.name, field);
    func.basic.ids.set(field.id, field.name);

    // 编号配置信息
    if (field.xtype === FuncFieldTypeEnum.INPUT_CODE.type) {
      func.fields.codeGenFieldInfo.push({
        code: field.name,
        configInfo: field.configInfo,
        ...pick(func.info, ['funcId', 'funcCode', 'funcName', 'tableCode']),
      });
      // 字典处理
    } else if (
      [
        FuncFieldTypeEnum.CHECKBOX_GROUP.type,
        FuncFieldTypeEnum.RADIO_GROUP.type,
        FuncFieldTypeEnum.SELECT.type,
      ].includes(field.xtype)
    ) {
      const ddCode = field.configInfo?.split(',')[0];
      func.basic.dictionarys.set(field.code, ddCode);
    } else if (field.xtype === FuncFieldTypeEnum.FUNC_CHILD_FIELD.type) {
      // 子功能集合
      const funcCode = field.configInfo?.split(',')[0];
      func.fields.childFunc.push({
        code: field.name,
        configInfo: field.configInfo,
        funcCode,
        autoLoad: false,
      });
    }

    // 默认值
    if (field.isBeanField()) {
      func.defaults.values[field.name] = field.getDefaultValue();
    }

    // 表达式
    if (field.expsEnable) {
      func.fields.exps.push(field.name);
    }

    // 锚点处理
    if (field.xtype === FuncFieldTypeEnum.FUNC_CHILD.type) {
      func.fields.anchor.push('__child__'); // 增加占位符，后面处理子功能
    } else if (field.xtype === FuncFieldTypeEnum.FIELDSET.type && !field.hidden && field.anchor) {
      func.fields.anchor.push({ key: field.name, text: field.label });
    }

    return field;
  });
  // 解析展示的字段
  func.fields.form = parseDiaplayKeys(fields);
}

/**
 * 解析列表，表单展示项的key
 * @param {*} param0
 * @returns
 */
function parseDiaplayKeys(data, groupName = '', useHidden = false) {
  const items = [];
  data.forEach((item) => {
    const code = item.code;
    // 启用隐藏项
    if ((useHidden || !item.hidden) && item.groupName === groupName) {
      const children = parseDiaplayKeys(data, code, useHidden);
      if (children.length) {
        items.push({ code: code, children });
      } else {
        items.push(code);
      }
    }
  });
  return items;
}

/**
 * 根据key获得原始数据
 * @param {*} param
 * @param {*} param.tiled 平铺数据
 * @returns
 */
export function keyToData({ keys, sourceMap, tiled = false }) {
  const items = [];
  keys.forEach((key) => {
    if (key.code) {
      const item = sourceMap.get(key.code);
      const children = keyToData({ keys: key.children, sourceMap, tiled });
      if (tiled) {
        items.push(item, ...children);
      } else {
        item.children = children;
        items.push(item);
      }
    } else {
      items.push(sourceMap.get(key));
    }
  });
  return items;
}
/**
 * 解析功能脚本
 * @param {*} data
 * @returns
 */
export function parseEvents(data) {
  let items = decode(data) ?? [];
  // 兼容旧数据
  if (isPlainObject(items)) {
    items = [items];
  }
  const events = {};
  items.forEach?.((item) => {
    if (item.fire == '1' && isNotEmpty(item.func)) {
      events[formatEventName(item.code)] = item.func;
    }
  });
  return events;
}

/**
 * 树形功能配置
 */
export function parseFuncTreeConfig(config) {
  const funcTreeConfig = {
    parent: 'SY_PARENT',
    nodePath: 'SY_PATH',
    nodeType: 'SY_NODETYPE',
    layer: 'SY_LAYER',
  };
  decode(config || '[]').forEach((item) => {
    funcTreeConfig[item.code] = item.value;
  });

  return funcTreeConfig;
}

/**
 * 格式化事件名称，统一使用kebab命名
 * @param {*} name
 * @param {*} on
 * @returns
 */
export function formatEventName(name, on) {
  return on ? camelCase(`on-${name}`) : kebabCase(name);
}

/**
 * 解析原始数据
 * @param {*} item
 */
function parseMetaData(item) {
  const metaData = {};
  for (let p in item) {
    const val = item[p];
    if (!isFunction(val)) {
      metaData[p] = isPlainObject(val) ? clone(val) : val;
    }
  }
  return metaData;
}

/**
 * 解析字段公共有效的配置
 * @param {*} field
 * @returns
 */
export function parseFieldProps({ field, $func }) {
  const props = {};
  ['disabled', 'configInfo', 'placeholder', 'selectExp', 'height', 'width', 'querys'].forEach(
    (key) => {
      if (isNotEmpty(field[key], true)) {
        props[key] = field[key];
      }
    },
  );
  const {
    inputType,
    pkName,
    winHeight,
    winWidth,
    cascadeType,
    optionalAndInput,
    optionalAndQuery,
  } = field.otherConfig;

  switch (field.xtype) {
    // 选择字段
    case FuncFieldTypeEnum.INPUT_SELECT_GRID.type:
    case FuncFieldTypeEnum.INPUT_SELECT_TREE.type:
    case FuncFieldTypeEnum.INPUT_SELECT_USER.type:
      // 文本域
      props.textarea = inputType === 'textarea';
      // 可选可输入
      props.editable = toBoolean(optionalAndInput);
      // 其他配置项
      props.selectOptions = {
        idProperty: pkName,
        width: winWidth > 0 ? winWidth : undefined,
        height: winHeight > 0 ? winHeight : undefined,
        cascadeType,
      };
      break;
    case FuncFieldTypeEnum.UPLOAD_INPUT.type: // 附件
      // const { fileBucket } = $func.getFuncData().info;
      const { fileSize, allow, notallow } = field.otherConfig;
      props.maxSize = toNumber(fileSize);
      props.includeSuffix = split(allow, ',');
      props.excludeSuffix = split(notallow, ',');
      // props.params = { bucket: fileBucket };
      break;
    case FuncFieldTypeEnum.INPUT_SELECT_COLOR.type: // 颜色选择器
      const colors = split(field.configInfo, ',');
      props.colors = colors.length ? colors : undefined;
      break;
    case FuncFieldTypeEnum.DATE_PICKER.type: // 日期
    case FuncFieldTypeEnum.TIME_PICKER.type: // 时间
      const picker = field.otherConfig.dateType;
      props.format = field.configInfo || undefined;
      if (picker) {
        props.picker = picker;
      }
      break;
    case FuncFieldTypeEnum.SELECT.type: // 下拉框
      // 可选可查询
      props.showSearch = toBoolean(optionalAndQuery);
      // 可选可输入
      props.editable = toBoolean(optionalAndInput);
      break;
    case FuncFieldTypeEnum.INPUT_NUMBER.type: // 数值框
      props.precision = field.configInfo ? toNumber(field.configInfo) : 0;
      break;
    // case FuncFieldTypeEnum.RADIO_GROUP.type: // 单选框
    // case FuncFieldTypeEnum.CHECKBOX_GROUP.type: // 复选框
    //   const { otherConfig } = field;
    //   const config = {};
    //   debugger;
    //   if (otherConfig.layoutStyle == 'gridLayout') {
    //     // 栅格布局;
    //     config.wrap = true;
    //     config.cols = otherConfig.showCloum;
    //   } else if (otherConfig.layoutStyle == 'singleLayout') {
    //     // 单行布局
    //   } else {
    //     // 流式布局
    //     config.wrap = true;
    //   }
    //   Object.assign(props, config);
    //   break;
  }

  return props;
}

/**
 * v-model
 * @param {*} param0
 * @returns
 */
export function useModelValue({ model, key }) {
  return {
    value: toDefaultValue(model[key]) || model[key],
    'onUpdate:value': function (val) {
      model[key] = toDefaultValue(val) || val;
    },
  };
}
